#include "mainwindow.h"
#include "ui_mainwindow.h"


#define VIDEO_WIDTH 1920
#define VIDEO_HEIGHT 1080

extern "C" {

    #include <libavutil/imgutils.h>
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    SDL_Init(SDL_INIT_VIDEO);


    ;
    window = SDL_CreateWindowFrom((void *)ui->label->winId());

    if(window == nullptr) {

        qDebug() << "SDL_CreateWindow fail";
        return;
    }

    renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC);


    if(renderer == nullptr) {

        renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_SOFTWARE);
    }


    if(renderer == nullptr) {

        qDebug() << "SDL_CreateRenderer fail";
        SDL_DestroyWindow(window);
        return;
    }


    texture = SDL_CreateTexture(renderer,SDL_PIXELFORMAT_IYUV,SDL_TEXTUREACCESS_STREAMING,VIDEO_WIDTH,VIDEO_HEIGHT);

    if(texture == nullptr) {

        qDebug() << "SDL_CreateTexture";
        SDL_DestroyWindow(window);
        SDL_DestroyRenderer(renderer);
        return;
    }

    const char* yuvPath = "/Users/tgy/Documents/ffmpeg/video/output.yuv";
//    QFile file(yuvPath);
    file = new QFile(yuvPath);

    if(!file->open(QFile::ReadOnly)){

        qDebug() << yuvPath << " open fail";

        SDL_DestroyWindow(window);
        SDL_DestroyRenderer(renderer);
        SDL_DestroyTexture(texture);
        SDL_Quit();
        return;
    }
}

MainWindow::~MainWindow()
{
    delete ui;

    if(file != nullptr) {

        file->close();
        file = nullptr;
    }

    SDL_DestroyRenderer(renderer);
    SDL_DestroyTexture(texture);



    SDL_SetRenderDrawColor(renderer,0,0,0,255);

    SDL_RenderClear(renderer);
}


void MainWindow::on_pushButton_clicked()
{

   timer = startTimer(15);
}

void MainWindow::timerEvent(QTimerEvent *event)
{
    int imageBufferSize = av_image_get_buffer_size(AV_PIX_FMT_YUV420P,VIDEO_WIDTH,VIDEO_HEIGHT,1);

    char buffer[imageBufferSize];
    int len = file->read(buffer,imageBufferSize);

    if(len <=0) {

        killTimer(timer);
        return;
    }

    qDebug() << "len " << len;

    SDL_UpdateTexture(texture,nullptr,buffer,VIDEO_WIDTH);

    SDL_RenderCopy(renderer,texture,nullptr,nullptr);

    SDL_RenderPresent(renderer);
}
